#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>

int number = 0;
int MAX = 20;

std::mutex g_lock;

int fun1()
{
    while (number < MAX)
    {
        // g_lock.lock();
        {
            std::lock_guard<std::mutex> lg(g_lock);
            // std::cout << "thread 1: " << number << "\n";
            std::cout << "thread 1: " << number << std::endl;
            ++number;
        }
        // g_lock.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    return 0;  
}

int fun2()
{
    while (number < MAX)
    {
        // g_lock.lock();
        {
            std::lock_guard<std::mutex> lg(g_lock);
            // std::cout << "thread 2: " << number << "\n";
            std::cout << "thread 2: " << number << std::endl;
            ++number;
        }
        // g_lock.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    return 0;  
}

int main(int argc, char **argv)
{
    std::thread t1(fun1);
    std::thread t2(fun2);

    t1.join();
    t2.join();

    return 0;
}